package com.liuche.homechat.common.user.aspect;

import com.liuche.homechat.common.common.exception.BusinessErrorEnum;
import com.liuche.homechat.common.common.exception.BusinessException;
import com.liuche.homechat.common.common.exception.ErrorEnum;
import com.liuche.homechat.common.common.model.dto.RequestInfo;
import com.liuche.homechat.common.common.utils.RequestHolder;
import com.liuche.homechat.common.user.annotation.Permission;
import com.liuche.homechat.common.user.dao.UserRoleDao;
import com.liuche.homechat.common.user.domain.entity.UserRole;
import com.liuche.homechat.common.user.service.UserRoleService;
import com.liuche.homechat.common.user.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author：liuche
 * @Date：2024年06月08日 17:29
 * @Description：权限校验
 */
@Aspect
@Component
public class PermissionAspect {
    @Resource
    private UserRoleService userRoleService;

    @Around(value = "@annotation(com.liuche.homechat.common.user.annotation.Permission)")
    public Object handleRedisLock(ProceedingJoinPoint joinPoint) throws Throwable {
        // 通过反射机制获取到注解对象
        Permission annotation = ((MethodSignature) joinPoint.getSignature())
                .getMethod()
                .getAnnotation(Permission.class);

        // 得到方法标注的用户操作等级
        int level = annotation.level();

        // 得到当前用户权限信息
        RequestInfo userInfo = RequestHolder.get();
        UserRole userRole = userRoleService.queryUserRoleByUid(userInfo.getUid());
        Long role = userRole.getRoleId();
        if (role <= level) {
            // 满足：当前用户是超级管理员用户或者权限大于等于当前方法设置的权限即可执行该方法
            return joinPoint.proceed(); // 如果权限检查通过，继续执行目标方法，并返回其结果
        } else {
            // 不满足：抛异常
            throw new BusinessException(BusinessErrorEnum.USER_NOT_PERMISSION);
        }
    }
}
